#include <iostream>
#include <cstdio>
#include <string>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}


// 阻塞
int main()
{
    std::string tips = "Please Enter# ";
    char buffer[1024];
    SetNonBlock(0);
    while(true)
    {
        write(0, tips.c_str(), tips.size());
        // 非阻塞，如果不输入数据，数据不就绪，就以出错形式返回
        // 区分数据不就绪和出错 通过错误码
        int n = read(0, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout<<"echo# "<<buffer<<std::endl;
        }
        else if(n == 0)
        {
            std::cout<<"read file end!"<<std::endl;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout<<"底层数据没有就绪"<<std::endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR)
            {
                std::cout<<"被中断, 重来"<<std::endl;
                sleep(1);
                continue;
            }
            else
            {
                std::cout<<"read error!"<<"errno: "<<errno<<std::endl;
            }
            
        }
        sleep(1);
    }

    return 0;
}